package basis.netease.easy;

import java.util.Scanner;

/**
 * 7-18 最长回文子串
 * 给你一个字符串s，找到s中最长的回文子串。
 * 如果字符串的反序与原始字符串相同，则该字符串称为回文字符串。
 * 输入格式:
 * 1<=s.length<=1000
 * 输出格式:
 * s中最长的回文子串
 * 输入样例:
 * 在这里给出一组输入。例如：
 * zyrcbabd
 * 输出样例:
 * 在这里给出相应的输出。例如：
 * bab
 */
public class Main_15 {
    public static String longestPalindrome(String s) {
        if (s == null || s.isEmpty()) {
            return s;
        }
        int n = s.length();
        int maxLength = 1;
        int start = 0;
        boolean[][] dp = new boolean[n][n];
        for (int i = 0; i < n; i++) {
            dp[i][i] = true;
        }
        for (int length = 2; length <= n; length++) {
            for (int startIdx = 0; startIdx < n - length + 1; startIdx++) {
                int endIdx = startIdx + length - 1;
                if (length == 2) {
                    dp[startIdx][endIdx] = (s.charAt(startIdx) == s.charAt(endIdx));
                } else {
                    dp[startIdx][endIdx] = (s.charAt(startIdx) == s.charAt(endIdx) && dp[startIdx + 1][endIdx - 1]);
                }
                if (dp[startIdx][endIdx] && length > maxLength) {
                    maxLength = length;
                    start = startIdx;
                }
            }
        }
        return s.substring(start, start + maxLength);
    }

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        String result = longestPalindrome(in.nextLine());
        System.out.println(result);
    }

    public static String longestPalindrome2(String s) {
        if (s == null || s.length() < 1) {
            return "";
        }
        int start = 0, end = 0;
        for (int i = 0; i < s.length(); i++) {
            int len1 = expandAroundCenter(s, i, i);
            int len2 = expandAroundCenter(s, i, i + 1);
            int len = Math.max(len1, len2);
            if (len > end - start) {
                start = i - (len - 1) / 2;
                end = i + len / 2;
            }
        }
        return s.substring(start, end + 1);
    }

    private static int expandAroundCenter(String s, int left, int right) {
        while (left >= 0 && right < s.length() && s.charAt(left) == s.charAt(right)) {
            left--;
            right++;
        }
        return right - left - 1;
    }
}
